Unity webgl 嵌入Vue实现过程 | 您所在的位置:网站首页 › unity嵌入网页 支持WEBGL › Unity webgl 嵌入Vue实现过程 |
需求分析:
Unity webgl嵌入到前端网页中,前端通过调用Unity webgl内方法实现需要展示的功能,前端点击Unity webgl内的交互点,Unity webgl返回给前端一些需要的数据。 例如:当我们需要在三维场景中展示库区中一些监控设备的部署位置,通过点击三维场景中的监控按钮打开当前监控设备的实时画面,一般情况下打开监控需要传递当前监控的IP或者通道号,这时Unity webgl向前端返回数据就用到了。 实现过程: 1、Unity webgl向Vue发送数据首先,Unity webgl向前端发送数据需要定义一个.jslib格式文件作为转接,文件名自取(建议不要用中文)文件内容如下: 到此,转接文件已经定义好了 接着在Unity脚本中添加 using System.Runtime.InteropServices; 引用(用于COM互操作), 代码如下: using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class Test: MonoBehaviour { [DllImport("__Internal")] private static extern void UnitySendMessage(string eventname, string data);//方法名及参数和转接的.jslib文件中的一样 private Button button; private void Awake() { button.onClick.AddListener(SendMessage); } private void SendMessage() { UnitySendMessage("getbuttonname",GetButtonName());//事件名自己命名即可,前端在监听时使用 } private string GetButtonName() { string name = EventSystem.current.currentSelectedGameObject.name; return name; } }打包后打开index.html文件加入此段代码: window.ReportReady = function (eventname, data) { var initD = { detail: { data } } var evt = new CustomEvent(eventname, initD) window.top.dispatchEvent(evt) }如图: 最后在Vue mounted中加入即可 window.addEventListener('getbuttonname', this.uinityEvent, false)//getbuttonname对应Unity内定义的事件名 2、Vue向Unity发送数据首先,Vue调用Unity的方法就比较简单了,在Unity内定义带参数的方法如: using UnityEngine; public class Test: MonoBehaviour { private void GetVueData(string value) { Debug.Log(value); } }接着打开打包后的index.html文件,在里面加入供前端调用的方法: function GetVueMessage(obj) { UnityInstanceV.SendMessage('MainSenceScript', 'GetVueData', JSON.stringify(obj)) //对应的参数分别为:"Unity场景内挂载脚本的物体名字","方法名",最后一个参数复制粘贴即可 }最后只需Vue调用此方法并传递参数就可以了,如果这篇文章帮助到你,就点个赞吧! |
CopyRight 2018-2019 实验室设备网 版权所有 |